package com.lifeverse.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.TimeUnit;

/**
 * 缓存配置
 * 使用 Caffeine 作为本地缓存实现
 */
@Configuration
@EnableCaching
public class CacheConfig {
    
    /**
     * 默认缓存管理器
     */
    @Bean
    @Primary
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(defaultCaffeineBuilder());
        return cacheManager;
    }
    
    /**
     * 性能指标缓存管理器
     */
    @Bean("performanceCacheManager")
    public CacheManager performanceCacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(performanceCaffeineBuilder());
        cacheManager.setCacheNames(java.util.List.of(
                "performanceMetrics",
                "systemHealth",
                "performanceRecommendations",
                "metricStatistics",
                "performanceTrends"
        ));
        return cacheManager;
    }
    
    /**
     * 数据库查询缓存管理器
     */
    @Bean("databaseCacheManager")
    public CacheManager databaseCacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(databaseCaffeineBuilder());
        cacheManager.setCacheNames(java.util.List.of(
                "lifeEntityCache",
                "digitalDnaCache",
                "consciousnessStateCache",
                "relationshipCache",
                "decisionCache"
        ));
        return cacheManager;
    }
    
    /**
     * 默认 Caffeine 配置
     */
    private Caffeine<Object, Object> defaultCaffeineBuilder() {
        return Caffeine.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(30, TimeUnit.MINUTES)
                .expireAfterAccess(10, TimeUnit.MINUTES)
                .recordStats();
    }
    
    /**
     * 性能指标 Caffeine 配置
     */
    private Caffeine<Object, Object> performanceCaffeineBuilder() {
        return Caffeine.newBuilder()
                .maximumSize(5000)
                .expireAfterWrite(5, TimeUnit.MINUTES)
                .expireAfterAccess(2, TimeUnit.MINUTES)
                .recordStats();
    }
    
    /**
     * 数据库查询 Caffeine 配置
     */
    private Caffeine<Object, Object> databaseCaffeineBuilder() {
        return Caffeine.newBuilder()
                .maximumSize(2000)
                .expireAfterWrite(60, TimeUnit.MINUTES)
                .expireAfterAccess(30, TimeUnit.MINUTES)
                .recordStats();
    }
}